// HSS.Logging.AutoTruncateService.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       AutoTruncateService.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/04/2010
// ----------------------------------------------------------------------------
using System;
using HSS.Data;
using HSS.Threading;

namespace HSS.Logging
{
    internal class AutoTruncateService : ITimerService
    {
        #region Fields
		static AutoTruncateService timerService;
        static TimerSchedule schedule;
		static Timer timer;
		#endregion

        #region Constructors
        /// <summary>
        /// Private CTOR
        /// </summary>
        private AutoTruncateService()
        {
        }
        #endregion

		#region Properties
		/// <summary>
		/// Has the AutoRestartService been started.
		/// </summary>
		public static bool IsStarted
		{
			get { return AutoTruncateService._isStarted; }
		} static bool _isStarted;
		#endregion

		#region Methods
		/// <summary>
        /// Start the AutoTruncateService
        /// </summary>
		/// <param name="TimeOfDay">The Time of the day in which to truncate the Log</param>
		public static void Start(DateTime TimeOfDay)
		{
			if (_isStarted) return;
			try
			{
				schedule = new TimerSchedule(TimeOfDay);
				timerService = new AutoTruncateService();
				timer = new Timer(timerService, schedule);
				timer.Start();
				_isStarted = true;
			}
			finally { }
		}
        /// <summary>
        /// Stop the AutoTruncateService
        /// </summary>
		public static void Stop()
        {
			if (null != timer)
			{
				try { timer.Stop(); }
				catch { }
				try { timer.Dispose(); }
				catch {}
				timerService = null;
				schedule = null;
				timer = null;
			}
			_isStarted = false;
		}
        #endregion

        #region ITimerService Members

        /// <summary>
        /// This method is called by the timer when it's time to run based on the schedule configuration
        /// </summary>
        /// <param name="sourceTimer">The source timer</param>
        public void OnTick(Timer sourceTimer)
        {
            Program.TruncateLog();
        }

        #endregion
	}
}